package com.yunxi.core.util;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2019/5/9.
 */

public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    /*   @Value("${http.connectTimeout}")
       private Integer connectTimeout;
       @Value("${http.connectionRequestTimeout}")
       private Integer connectionRequestTimeout;
       @Value("${http.SocketTimeout}")
       private Integer socketTimeout;
       @Value("${http.url}")
       private String url;
       @Value("${http.contentType}")
       private String contentType;*/
    private static Integer connectTimeout = 1000;

    private static Integer connectionRequestTimeout = 500;

    private static Integer socketTimeout = 10000;

    //private String url="http://10.64.19.85:7080/esb/ehr/api";

    private static String contentType = "application/json";

    @SuppressWarnings("unused")
    public static void main(String[] args) {
      /*  String url ="http://10.64.19.85:7080/esb/ehr/api";
        String jsonStr ="{\"StartTime\":\"2019-01-28T06:07:31.660Z\",\"StopTime\":\"2019-01-29T06:07:31.660Z\",\"WithDisabled\":true,\"WithDeleted\":true,\"PageIndex\":1,\"PageSize\":10,\"Sort\":{},\"ExtParams\":{},\"Columns\":[\"Name\"]}";
        String contentType = "application/json";
        String res= HttpUtil.sendPost(url,jsonStr,contentType);
        System.out.println("返回信息:"+res);*/

    }

    public static Map sendPost(String bodyStr, String serviceName, String sourceSystem, String url) throws IOException {
        Map map = new HashMap();
        StringBuffer resultBuffer = null;
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        //设设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", contentType);
        String requestId = UUID.randomUUID().toString();
        httpPost.addHeader("requestId", requestId);
        httpPost.addHeader("serviceName", serviceName);
        httpPost.addHeader("sourceSystem", sourceSystem);
        BufferedReader br = null;
        Map header = null;
        StringEntity entity = new StringEntity(bodyStr, "UTF-8");
        httpPost.setEntity(entity);
        long start = System.currentTimeMillis();
        HttpResponse response = null;
        try {
            response = client.execute(httpPost);
            header = getHeader(response);
            long time = System.currentTimeMillis() - start;
            logger.debug("本次请求'{}'耗时:{}ms", url, time);
            resultBuffer = new StringBuffer();
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
        } catch (ClientProtocolException e) {
            logger.error("ClientProtocolException:", e);
            logger.warn("-----------------请求出现异常:{}-----------------", e.toString());

        } catch (IOException e) {
            logger.error("IOException:", e);
            logger.warn("-----------------请求出现IO异常:{}-----------------", e.toString());

        } catch (Exception e) {
            logger.error("Exception:", e);
            logger.warn("-----------------请求出现其他异常:{}-----------------", e.toString());

        } finally {
            //abort the request
            if (null != httpPost && !httpPost.isAborted()) {
                httpPost.abort();
            }
            //close the connection
            HttpClientUtils.closeQuietly(client);
            HttpClientUtils.closeQuietly(response);
        };
        map.put("response",String.valueOf(resultBuffer));
        map.put("header", header);
        map.put("requestId", requestId);
        return map;
    }


    public static Map sendUpsPost(String bodyStr, String serviceName, String sourceSystem, String url,String iamSystem) throws IOException {
        Map map = new HashMap();
        StringBuffer resultBuffer = null;
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        //设设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", contentType);
        String requestId = UUID.randomUUID().toString();
        httpPost.addHeader("requestId", requestId);
        httpPost.addHeader("serviceName", serviceName);
        httpPost.addHeader("sourceSystem", sourceSystem);
        httpPost.addHeader("iamSystem", iamSystem);
        BufferedReader br = null;
        Map header = null;
        StringEntity entity = new StringEntity(bodyStr, "UTF-8");
        httpPost.setEntity(entity);
        long start = System.currentTimeMillis();
        HttpResponse response = null;
        try {
            response = client.execute(httpPost);
            header = getHeader(response);
            long time = System.currentTimeMillis() - start;
            logger.debug("本次请求'{}'耗时:{}ms", url, time);
            resultBuffer = new StringBuffer();
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
        } catch (ClientProtocolException e) {
            logger.error("ClientProtocolException:", e);
            logger.warn("-----------------请求出现异常:{}-----------------", e.toString());

        } catch (IOException e) {
            logger.error("IOException:", e);
            logger.warn("-----------------请求出现IO异常:{}-----------------", e.toString());

        } catch (Exception e) {
            logger.error("Exception:", e);
            logger.warn("-----------------请求出现其他异常:{}-----------------", e.toString());

        } finally {
            //abort the request
            if (null != httpPost && !httpPost.isAborted()) {
                httpPost.abort();
            }
            //close the connection
            HttpClientUtils.closeQuietly(client);
            HttpClientUtils.closeQuietly(response);
        };
        map.put("response",String.valueOf(resultBuffer));
        map.put("header", header);
        map.put("requestId", requestId);
        return map;
    }

    public static String sendGet(String paramData, String serviceName, String sourceSystem, String url) {
        StringBuffer resultBuffer = null;
        HttpClient client = new DefaultHttpClient();
        String getUrl = url;
        if (null != paramData) {
            getUrl += "?" + paramData;
        }
        HttpGet httpGet = new HttpGet(getUrl);
        //设设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpGet.setConfig(requestConfig);
        httpGet.addHeader("Content-Type", contentType);
        httpGet.addHeader("requestId", UUID.randomUUID().toString());
        httpGet.addHeader("serviceName", serviceName);
        httpGet.addHeader("sourceSystem", sourceSystem);
        BufferedReader br = null;
        try {
            long start = System.currentTimeMillis();
            HttpResponse response = client.execute(httpGet);
            long time = System.currentTimeMillis() - start;
            logger.debug("本次请求'{}'耗时:{}ms", url, time);
            //close the connection
            HttpClientUtils.closeQuietly(client);
            HttpClientUtils.closeQuietly(response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }

        return resultBuffer.toString();
    }
    public static String sendHttpsGet(String url) {
        StringBuffer resultBuffer = null;

        String getUrl = url;
        HttpGet httpGet = new HttpGet(getUrl);
        //设设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(500000).setConnectionRequestTimeout(500000)
                .setSocketTimeout(500000).build();
        HttpClient client;
        client= createCloseableHttpClient(url,requestConfig);
        BufferedReader br = null;
        try {
            long start = System.currentTimeMillis();
            HttpResponse response = client.execute(httpGet);
            long time = System.currentTimeMillis() - start;
            resultBuffer = new StringBuffer();
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
            HttpClientUtils.closeQuietly(client);
            HttpClientUtils.closeQuietly(response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }
    public static String sendHttpsPost(String url,String paramData) {
        StringBuffer resultBuffer = null;

        String getUrl = url;
        HttpPost httpPost = new HttpPost(getUrl);
        if(paramData != null){
            StringEntity jsonEntity = new StringEntity(paramData, ContentType.APPLICATION_JSON);
            httpPost.setEntity(jsonEntity);
        }
        //设设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(500000).setConnectionRequestTimeout(500000)
                .setSocketTimeout(500000).build();
        HttpClient client;
        client= createCloseableHttpClient(url,requestConfig);
        BufferedReader br = null;
        try {
            long start = System.currentTimeMillis();
            HttpResponse response = client.execute(httpPost);
            long time = System.currentTimeMillis() - start;
            resultBuffer = new StringBuffer();
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
            HttpClientUtils.closeQuietly(client);
            HttpClientUtils.closeQuietly(response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }
    private static CloseableHttpClient createCloseableHttpClient(String finalUrl, RequestConfig config){
        HttpClientBuilder builder = HttpClients.custom();
        builder.setDefaultRequestConfig(config);
        if (finalUrl.startsWith("https")) {
            try {
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    // 信任所有
                    public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        return true;
                    }
                }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                builder.setSSLSocketFactory(sslsf);
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyStoreException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return builder.build();
    }

    private static Map getHeader(HttpResponse response) {
        Map map = new HashMap();
        Header[] allHeaders = response.getAllHeaders();
        for (int i = 0; i < allHeaders.length; i++) {
            Header allHeader = allHeaders[i];
            map.put(allHeader.getName(), allHeader.getValue());
        }
        System.err.println(map);
        return map;
    }
}
